<template>
  <div class="uploadImg">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="imageUrl"
        v-imgError="defaultImg"
        :src="imageUrl"
        class="avatar"
        @click.stop="showBigImage"
      >
      <!-- v-imgError="defaultImg" 加入自定义指令图片出错处理 -->
      <!-- .stop绑定图片的点击事件 阻止冒泡 -->
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- v-if="imageUrl" 有图片时才显示关闭 -->
    <div v-if="imageUrl" class="close" @click="closeEvent">X</div>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="isShow" title="图片预览">
      <div style="text-align: center">
        <img class="img" :src="imageUrl">
      </div>
    </el-dialog>
    <!-- 加入进度条 -->
    <!-- 加上name="progressBar"就是css的前缀 -->
    <!-- .progressBar-enter-active:进入过程中一直存在 进入动画的执行体 用于承载transition animation -->
    <!-- .progressBar-leave-active:离开过程中一直存在 离开动画的执行体 用于承载transition animation -->
    <!-- .progressBar-enter:进入前状态 进入前希望从什么状态编导正常状态-->
    <!-- .progressBar-leave-to:离开时状态 离开时希望从正常状态变到什么状态-->

    <transition name="progressBar">
      <el-progress v-if="showProgress" :percentage="percentage" />
    </transition>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  SecretId: 'AKID84kAJBl46sNbYEcjZ8PQBgtpWx6yZsue',
  SecretKey: 'WliOnQmrfBPM2QXMvEFzRcW9UZMs63i6'
})
export default {
  name: 'UploadImg',
  model: {
    prop: 'imageUrl'
  },
  props: {
    // 通过props接收imageUrl 同时配制model的prop
    imageUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      percentage: 0, // 进度条变量值
      showProgress: false, // 是否显示进度条
      isShow: false,
      defaultImg: require('@/assets/common/yasuo.jpg')
      // imageUrl: '' 删除imageUrl变量
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      console.log(file)
      // 上传前 限制文件大小与类型
      const isPng =
        file.type === 'image/png' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg'
      const limit1M = file.size / 1024 / 1024 < 1
      if (!isPng) {
        this.$message.error('请上传png图片!')
      }
      if (!limit1M) {
        this.$message.error('请上传1M内图片!')
      }
      return isPng && limit1M
    },
    httpRequest(res) {
      // 显示上传进度
      this.showProgress = true
      this.percentage = 0 // 进度条值为0
      // res.file:上传文件对象
      console.log(res)
      cos.putObject(
        {
          Bucket: 'abc-1308460175',
          Region: 'ap-beijing',
          Key: res.file.uid + '',
          StorageClass: 'STANDARD',
          Body: res.file,
          onProgress: (progressData) => {
            // 上传进度
            this.percentage = progressData.percent * 100
            // progressData.percent=1 上传完成 上传过程中显示进度条的值
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.showProgress = false // 上传完成让进度条消失 等两秒后消失
              }, 2000)
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 上传成功或者失败的回调
          console.log(err || data)
          console.log('this', this)
          // this.imageUrl = 'http://' + data.Location
          this.$emit('input', 'http://' + data.Location)
        }
      )
    },
    // 删除图片功能
    closeEvent() {
      this.$emit('input', '')
    },
    // 点击图片打开dialog
    showBigImage() {
      this.isShow = true
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.uploadImg {
  position: relative;
  width: 178px;
  &:hover {
    .close {
      display: block;
    }
  }
  .close {
    display: none;
    position: absolute;
    top: 5px;
    right: 10px;
    cursor: pointer;
  }
  .img {
    width: 100%;
  }
}

.progressBar-enter-active,
.progressBar-leave-active {
  transition: all 0.5s;
}

.progressBar-enter,
.progressBar-leave-to {
  opacity: 0;
}
</style>
